import requests
from bs4 import BeautifulSoup as bs
from pyquery import PyQuery as pq
from sql_helper import MySqlHelper
import json


def read_list(url, item_dict_all=None):
    if item_dict_all is None:
        item_dict_all = []
        for url in url_list:

            if requests.get(url).status_code == 200:
                response = json.loads(requests.get(url).text)
                for item in response:
                    item_dict = []
                    item_dict.append(item['title'])
                    item_dict.append(item['cover'])
                    item_dict.append('https://douban.fm/songlist/'+str(item['id']))
                    item_dict_all.append(item_dict)
                print('ok')
            else:
                print("你抓的出问题了！")
    return item_dict_all


if __name__ == "__main__":
    url_list = ["https://douban.fm/j/v2/songlist/explore?type=hot&genre=0&limit=20&sample_cnt=5",
                "https://douban.fm/j/v2/songlist/explore?type=hot&genre=2&limit=20&sample_cnt=5",
                "https://douban.fm/j/v2/songlist/explore?type=hot&genre=4&limit=20&sample_cnt=5"
                ]
    item_all = read_list(url_list)

    mysql = MySqlHelper()
    sql = "INSERT INTO musics(title, cover, intro) VALUES(%s,%s,%s)"
    mysql.exec_many(sql, item_all)
